//
//  NotificationService.m
//  myNotificationService
//
//  Created by huzhaoke1 on 2023/10/31.
//

#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVFAudio.h>
#import <AVFoundation/AVFAudio.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "HKCommonDefine.h"
#import "XSAudioManager.h"
#import <AVFoundation/AVFoundation.h>
#import "HKShareAvaudioManager.h"
#define kFileManager [NSFileManager defaultManager]

typedef void(^PlayVoiceBlock)(void);

@interface NotificationService ()<UNUserNotificationCenterDelegate,AVAudioPlayerDelegate>
 

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

//// AVSpeechSynthesisVoice 播放完毕之后的回调block
//@property (nonatomic, copy)PlayVoiceBlock finshBlock;
////声音文件的播放器
@property (nonatomic, strong)AVAudioPlayer *audioPlayer;
////声音文件的路径
//@property (nonatomic, strong) NSString *filePath;

@property (nonatomic, assign) NSInteger playTimes;

@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) dispatch_source_t timer;
@property  SystemSoundID soundID;
@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    [[AVAudioSession sharedInstance] setActive:YES error:NULL];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    NSString *path =  [[NSBundle mainBundle] pathForResource:@"star_show30sec.wav" ofType:nil];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &_soundID);
    AudioServicesAddSystemSoundCompletion(_soundID, NULL, NULL, soundCompleteCallback, NULL);
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(_soundID);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    __block NSInteger time = 28;
    self.queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
    dispatch_source_set_timer(self.timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
         if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                AudioServicesDisposeSystemSoundID(self.soundID);
                AudioServicesRemoveSystemSoundCompletion(self.soundID);
                AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
                AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                time--;
                NSLog(@"%ld",(long)time);
             });
        }
    });
    dispatch_resume(self.timer);
    
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    self.bestAttemptContent.sound = nil;
//    self.bestAttemptContent.sound = [UNNotificationSound soundNamed:@"star_show30sec.wav"];
    self.contentHandler(self.bestAttemptContent);
}

//将要推送
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSLog(@"----------willPresentNotification");
}
 
//已经完成推送
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{

}

void soundCompleteCallback(SystemSoundID sound, void *clientDate) {
    if (sound == kSystemSoundID_Vibrate) {
        AudioServicesPlayAlertSound(sound); // 重复响铃震动
    } else {
        AudioServicesDisposeSystemSoundID(sound);
        AudioServicesRemoveSystemSoundCompletion(sound);
        
        AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
        AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
     }
}

@end
